package com.erp.gather.listener;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.gather.domain.ErpAutoCollectProductTemporary;
import com.erp.gather.domain.vo.ErpCollectProductExpandVo;
import com.ruoyi.gather.api.domain.vo.ErpCollectProductSkuVo;
import com.erp.gather.mapper.*;
import com.rabbitmq.client.Channel;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.auto.api.RemoteAutoPublishProductService;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.gather.api.domain.dto.TaskStatusDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static jodd.util.ThreadUtil.sleep;

/**
 * 监听路由信息
 *
 * @Author: j.zh
 * @Date: 2024/3/12
 * @Version: 1.0
 **/
@Slf4j
@Component
@RabbitListener(queues = "auto.seller.product.queue", ackMode = "MANUAL")
public class AutoSellerProductListener {
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    ErpSellerProductMapper erpSellerProductMapper;
    @Resource
    ErpCollectProductMapper erpCollectProductMapper;
    @Resource
    ErpCollectProductSkuMapper erpCollectProductSkuMapper;
    @Resource
    ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    @Resource
    ErpAutoCollectProductTemporaryMapper erpAutoCollectProductTemporaryMapper;
    @Resource
    ErpSellerProductSkuMapper erpSellerProductSkuMapper;
    @Resource
    ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    @Resource
    RemoteAutoPublishProductService remoteAutoPublishProductService;
    @Resource
    private RabbitTemplate rabbitTemplate = SpringUtils.getBean(RabbitTemplate.class);

    /**
     * 公共库至个人库
     *
     * @param info
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(String info, Channel channel, Message message) throws IOException {

        try {
            System.out.println("=============接收消息，消息队列开始执行（公共库至个人库）");
            // 回复队列消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 将JSON字符串转换为实体类
            AeAutoProductDto dto = JSONObject.parseObject(info, AeAutoProductDto.class);
            // 执行公共库至个人库操作
            R<Object> resultOne = publish(dto);
            if (resultOne.getCode() == 500) {
                System.out.println("=============执行失败:" + resultOne.getMsg());
            }
        } catch (Exception e) {
            // TODO 消费异常，设置入库操作

            System.out.println("=============执行异常：" + e.toString());
        }

    }

    /**
     * 刊登至个人产品库
     *
     * @param dto
     */
    @Async("publishToSPMq")
    public R<Object> publish(AeAutoProductDto dto) {
        Long storeId = dto.getStoreId();
        Long aeProductId = dto.getAeProductId();
        R<Object> AuditType = findAeProductStatusById(aeProductId, storeId);
        if (AuditType.getCode() != 200) {
            System.out.println("开始休眠五秒获取状态：" + dto.getAeProductId());
            sleep(5000);
            System.out.println("结束休眠：" + dto.getAeProductId());
            AuditType = findAeProductStatusById(aeProductId, storeId);
        }
        System.out.println(AuditType.getCode());
        if (AuditType.getCode() != 200) {
            // 下架商品
            remoteAeProductService.productOffline(aeProductId, storeId);
            // 删除产品
            remoteAeProductService.deleteProductToAe(aeProductId, storeId);
            //返回消息给task任务
            TaskStatusDto taskStatusDto = new TaskStatusDto();
            taskStatusDto.setStatus(5);
            taskStatusDto.setMsg("|产品进入审核中状态，系统将其自动下架并删除");
            taskStatusDto.setId(dto.getAutoTaskId());

            //标记侵权品
            //1、从临时表中删除
            ErpAutoCollectProductTemporary temporary = erpAutoCollectProductTemporaryMapper.selectOne(
                    new LambdaQueryWrapper<ErpAutoCollectProductTemporary>()
                            .eq(ErpAutoCollectProductTemporary::getCollectProductId, dto.getCollectProductId())
            );
            erpAutoCollectProductTemporaryMapper.deleteById(temporary);
            ErpCollectProductExpand erpCollectProductExpand = dto.getCollectProductExpand();
//            if (dto.getProductType() == 1){
//                //2、在采集延伸中设为疑似侵权
//                erpCollectProductExpand.setIsViola(9);
//                erpCollectProductExpandMapper.updateById(erpCollectProductExpand);
//            }
            //3、对未执行的任务进行清除
            remoteAutoPublishProductService.deleteTortListByCollectProductId(dto.getCollectProductId());
            //修改任务状态
            remoteAutoPublishProductService.updateTaskStatus(taskStatusDto);
            return R.ok();
        }

        // 判断是否刊登过
        ErpSellerProduct sellerProduct = erpSellerProductMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId, dto.getCollectProductId())
                        .eq(ErpSellerProduct::getSellerId, dto.getSellerId()).last("limit 1"));
        if (sellerProduct == null) {
            // 产品发布个人产品记录日志数据为发布中 TODO 这部分数据是自动化数据，考虑是否需要记录发布过程
//            publishTask = iErpCollectProductPublishTaskService.insertData(productId,
//                    sellerId, PublishType.ONGOING.getCode(), new Date(), null);

            // 替换相关图片为上传后的OSS链接
            ErpCollectProduct collectProduct = dto.getCollectProduct();
//        LambdaUpdateWrapper<ErpCollectProduct> luw = Wrappers.lambdaUpdate();
//        luw.set(ErpCollectProduct::getMarketing, dto.getMarketing());
//        luw.set(ErpCollectProduct::getImageURLs, dto.getImageURLs());
//        luw.set(ErpCollectProduct::getWhite, dto.getWhite());
//        luw.set(ErpCollectProduct::getDetailImg, dto.getDetailImg());
//        luw.eq(ErpCollectProduct::getId, dto.getCollectProductId());
//        erpCollectProductMapper.update(null, luw);

//            List<ErpCollectProductSku> erpCollectProductSkus = erpCollectProductSkuMapper
//                    .selectList(Wrappers.lambdaQuery(new ErpCollectProductSku())
//                            .eq(ErpCollectProductSku::getCollectProductId, collectProduct.getId()));
            // TODO 待补充SKU image
//            erpCollectProductSkus.forEach(erpCollectProductSku -> {
//                erpCollectProductSku.setSkuImage(dto.getSkuImage());
//                erpCollectProductSkuMapper.updateById(erpCollectProductSku);
//            });

            // 获取sku列表
//            List<ErpCollectProductSkuVo> productVoSkus = erpCollectProductSkuMapper
//                    .selectVoList(new LambdaQueryWrapper<ErpCollectProductSku>()
//                            .eq(ErpCollectProductSku::getCollectProductId, dto.getCollectProductId()));
            List<ErpCollectProductSkuVo> productVoSkus = dto.getCollectProductSkuList();
            // 获取产品扩展表
//            ErpCollectProductExpandVo collectProductExpandVo = erpCollectProductExpandMapper
//                    .selectVoOne(new LambdaQueryWrapper<ErpCollectProductExpand>()
//                            .eq(ErpCollectProductExpand::getCollectProductId, dto.getCollectProductId()));
            ErpCollectProductExpand collectProductExpandVo = dto.getCollectProductExpand();

            // 保存卖家商品库中
            ErpSellerProduct erpSellerProduct = new ErpSellerProduct();
            BeanUtils.copyProperties(collectProduct, erpSellerProduct);
            erpSellerProduct.setSellerId(dto.getSellerId());
            erpSellerProduct.setId(null);
            erpSellerProduct.setCollectProductId(dto.getCollectProductId());
            erpSellerProduct.setCreateTime(new Date());
            erpSellerProduct.setCreateBy("auto");
            erpSellerProduct.setSubject(dto.getSubject());
            erpSellerProduct.setDetail(dto.getDetail());

            //放入图片
            erpSellerProduct.setImageURLs(dto.getImageUrlsOld());
            erpSellerProduct.setWhite(dto.getWhiteOld());
            erpSellerProduct.setDetailImg(dto.getDetailImg());
            erpSellerProduct.setMarketing(dto.getMarketingOld());

            erpSellerProductMapper.insert(erpSellerProduct);

            Map<String, BigDecimal> skuPriceMap = new HashedMap<>();
            String freightMap = collectProductExpandVo.getFreightMap();
            List<Dict> freightMapList = JsonUtils.parseArrayMap(freightMap);

            // 获取运费，修改金额
            for (Dict dict : freightMapList) {
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                    // 添加sku价格
                    if (skuPriceMap.containsKey(key)) {
                        BigDecimal price = skuPriceMap.get(key);
                        if (price.compareTo(amount) == 1)
                            skuPriceMap.put(key, amount);
                    } else {
                        skuPriceMap.put(key, amount);
                    }
                }
            }

            // 保存sku
            for (ErpCollectProductSkuVo erpCollectProductSkuVo : productVoSkus) {
                ErpSellerProductSku erpSellerProductSku = new ErpSellerProductSku();
                BeanUtils.copyProperties(erpCollectProductSkuVo, erpSellerProductSku);
                erpSellerProductSku.setId(null);
                erpSellerProductSku.setSellerProductId(erpSellerProduct.getId());
                erpSellerProductSku.setCreateTime(new Date());
                erpSellerProductSku.setCreateBy("auto");

                String skuPropertyIds = erpSellerProductSku.getSkuPropertyIds();
                if (skuPriceMap.containsKey(skuPropertyIds)) {
                    BigDecimal minPrice = skuPriceMap.get(skuPropertyIds);

                    // 获取sku
                    BigDecimal skuPrice = new BigDecimal(erpSellerProductSku.getSkuPrice());
                    skuPrice = skuPrice.multiply(new BigDecimal(1.1));

                    // 计算最终价格
                    BigDecimal amount = skuPrice.add(minPrice.multiply(new BigDecimal(1.5))).setScale(2,
                            BigDecimal.ROUND_HALF_UP);
                    erpSellerProductSku.setSkuPrice(amount.toString());
                }

                erpSellerProductSkuMapper.insert(erpSellerProductSku);
            }

            // 保存商品扩展类
            ErpSellerProductExpand erpSellerProductExpand = new ErpSellerProductExpand();
            BeanUtils.copyProperties(collectProductExpandVo, erpSellerProductExpand);
            erpSellerProductExpand.setId(null);
            erpSellerProductExpand.setSellerProductId(erpSellerProduct.getId());
            erpSellerProductExpand.setAutoTaskId(dto.getAutoTaskId());
            erpSellerProductExpand.setCreateTime(new Date());
            erpSellerProductExpand.setCreateBy("auto");
            erpSellerProductExpandMapper.insert(erpSellerProductExpand);
            TaskStatusDto taskStatusDto = new TaskStatusDto();
            taskStatusDto.setStatus(2);
            taskStatusDto.setMsg("|从公共库刊登至个人库成功");
            taskStatusDto.setId(dto.getAutoTaskId());
            remoteAutoPublishProductService.updateTaskStatus(taskStatusDto);
        } else {
            TaskStatusDto taskStatusDto = new TaskStatusDto();
            taskStatusDto.setStatus(2);
            taskStatusDto.setMsg("|个人库原本存在数据");
            taskStatusDto.setId(dto.getAutoTaskId());
            remoteAutoPublishProductService.updateTaskStatus(taskStatusDto);
        }

        // 4.2 分发至gather业务模块，进行个人库至在线库操作
        log.info("开始分发至gather业务模块，进行个人库至在线库操作"+aeProductId);
        rabbitTemplate.convertAndSend("auto-event-exchange", "auto.seller.product.store.insert", JSONObject.toJSONString(dto));
        log.info("进行个人库至在线库操作结束"+aeProductId);

        return R.ok();
    }


    /**
     * 确认商品审核状态
     *
     * @param aeProductId
     * @param storeId
     * @return
     */
    public R<Object> findAeProductStatusById(Long aeProductId, Long storeId) {
        R<Object> aeProductR = remoteAeProductService.findAeProductStatusById(aeProductId, storeId);
        String msg = JSONObject.toJSONString(aeProductR.getData());
        System.out.println(msg);
        if (!msg.contains("approved")) {
            // 审核未通过或审核中
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }
}
